package guiPackage;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;

public class ResultatenScherm extends JPanel {
	private JTextPane textPane;
	private JScrollPane scrollPane;
	private JButton exportToDatabaseButton, terugButton;
	private Pattern patternTabelNaam;
	private Matcher matcherTabelNaam;
	private static final String QUERY_TABELNAAM_PATTERN = "(?i)^insert into ([A-Za-z]+) values";

	public ResultatenScherm(ArrayList<String> queries) throws BadLocationException {
		patternTabelNaam = Pattern.compile(QUERY_TABELNAAM_PATTERN);
		setLayout(new BorderLayout());
		textPane = new JTextPane();
		textPane.setEditable(false);
		scrollPane = new JScrollPane(textPane);
		String[] initStyles = { "regular", "italicbold" };
		StyledDocument doc = textPane.getStyledDocument();
		Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
		Style regular = doc.addStyle("regular", def);
		StyleConstants.setFontFamily(def, "SansSerif");
		StyleConstants.setFontSize(def, 15);
		Style s = doc.addStyle("italicbold", regular);
		StyleConstants.setBold(s, true);
		int style = 0;
		String huidigeTabelNaam = "";
		for (String query : queries) {
			String tabelNaam = "";
			matcherTabelNaam = patternTabelNaam.matcher(query);
			while(matcherTabelNaam.find()) {
				tabelNaam = matcherTabelNaam.group(1);
			}
			if (!huidigeTabelNaam.equals(tabelNaam)) {
				style++;
				huidigeTabelNaam = tabelNaam;
			}
			doc.insertString(doc.getLength(), query + "\n", doc.getStyle(initStyles[style % 2]));
		}
		scrollPane.setPreferredSize(new Dimension(900, 900));

		JPanel buttonPanel = new JPanel();
		buttonPanel.setLayout(new GridLayout(1, 2));
		exportToDatabaseButton = new JButton("Export to database");
		terugButton = new JButton("Terug");
		exportToDatabaseButton.setFont(new Font("sansserif", Font.BOLD, 30));
		terugButton.setFont(new Font("sansserif", Font.BOLD, 30));
		buttonPanel.add(terugButton);
		buttonPanel.add(exportToDatabaseButton);
		add(scrollPane, BorderLayout.NORTH);
		add(buttonPanel, BorderLayout.CENTER);
	}

	public void setListener(ActionListener listener) {
		exportToDatabaseButton.addActionListener(listener);
		terugButton.addActionListener(listener);
	}

	public JButton getExportToDatabaseButton() {
		return exportToDatabaseButton;
	}

	public JButton getTerugButton() {
		return terugButton;
	}
}
